﻿#include"MainController.h"
#include"MainModel.h"
#include"XQPortraitTreeDockWidget.h"
#include"XQUserManagementView.h"
#include"XQFuncEvent.h"
#include"XQFuncEventFilter.hpp"
#include"XQPictureWidget.h"
#include"XQCreateUserView.h"
#include"XQTablePagingWidget.h"
#include"XQLog.hpp"
#include"InventoryManagementView.h"
#include"InventoryView.h"
#include"ProductManagementView.h"
#include"ProductView.h"
#include"OrderManagementView.h"
#include<QTableWidget>
#include<QMessageBox>
#include<QIcon>
MainController::MainController(QObject* parent)
	:StashManageControllerObject(parent)
{
	init();
}
MainView* MainController::view()
{
	return m_mainView;
}
void MainController::login(const XQUserData& user)
{
	m_mainView->login(user);
}
void MainController::logout()
{
	m_mainView->logout();
}
void MainController::setModel(StashManageModelObject* model)
{
	if (model != nullptr&& view()!=nullptr)
	{
		view()->catalogue()->disconnect();
		connect(model->userInfo(), &XQUserInfo::portraitChangeSignals, view()->catalogue(), &XQPortraitTreeDockWidget::setPortrait);
		
	}
	StashManageControllerObject::setModel(model);
	this->model()->addMySqlThreadTask([=] {
		this->model<MainModel>()->initDatabaseTable();
		});
	
}
void MainController::copyModel(StashManageModelObject* model)
{
	if (model != nullptr && view() != nullptr)
	{
		view()->catalogue()->disconnect();
		connect(model->userInfo(), &XQUserInfo::portraitChangeSignals, view()->catalogue(), &XQPortraitTreeDockWidget::setPortrait);
	}
	StashManageControllerObject::copyModel(model);
	this->model()->addMySqlThreadTask([=] {
		this->model<MainModel>()->initDatabaseTable();
		});

}
void MainController::modifyUserInfoSlots(const XQUserData& user)
{
	auto newUser = model()->userData();
	newUser.setPortrait(user.portrait());
	newUser.setPhone(user.phone());
	newUser.setName(user.name());
	newUser.setGender(user.gender());
	model()->addMySqlThreadTask([=] 
		{
			model<MainModel>()->modifyUserInfoMySql(newUser);
		});
	model()->setUserData(newUser);
	m_mainView->setWindowTitle(user.name()+" 欢迎你");
	//m_mainView->setWindowIcon(QIcon(user.portrait()));
	emit sendMessageBoxInfoSignals("修改信息","修改成功");
	m_mainView->closeStackedWidget(MainView::View::UserInfo);
	
}
void MainController::modifyPasswordSlots(const XQUserData& user)
{
	auto newUser = model()->userData();
	newUser.setPassword(user.password());
	model()->addMySqlThreadTask([=]
		{
			model<MainModel>()->modifyUserInfoMySql(newUser);
		});
	model()->setUserData(newUser);
	emit sendMessageBoxInfoSignals("修改密码", "修改成功");
	m_mainView->closeStackedWidget(MainView::View::ModifyPassword);
	logout();
	emit requestLoginSignals();
}
void MainController::modifyUserManagementSlots(const XQUserData& user)
{
	//XQPictureWidget::showImage({user.portrait()});
	if (user.account() == model()->userData().account())
		model()->setUserData(user);
	model()->addMySqlThreadTask([=]
		{
			auto ok=model<MainModel>()->modifyUserInfoMySql(user);
			new XQFuncEvent(this, [=] {
				if(ok)
					emit sendMessageBoxInfoSignals(user.account() + " 修改信息", "修改成功");
				else
					emit sendMessageBoxInfoSignals(user.account() + " 修改信息", "更新失败");
				});
		});
	//
}
void MainController::addUserManagementSlots(const XQUserData& user)
{
	model()->addMySqlThreadTask([=]
		{
			XQUserData newUser;
			auto ok = model<MainModel>()->registerAccountMySql(user,&newUser);
			emit addUserResultSignals(user,ok);
			new XQFuncEvent(this, [=] {
				if (ok)
				{
					auto UserManagementView = (XQUserManagementView*)m_mainView->stackedWidget(MainView::View::UserManagement);
					auto UserAddView=(XQCreateUserView*)UserManagementView->transcribeWidget(XQUserManagementView::CreateWidget::UserAddView);
					UserAddView->close();//
					UserManagementView->addUser(newUser);
					UserManagementView->updataTable();
					QMessageBox::information(view(), user.account() + " 添加用户", "添加成功");
				}
				else
				{
					QMessageBox::information(view(), user.account() + " 添加用户", "添加失败");
				}
				});
		});
}
void MainController::removeUserManagementSlots(const XQUserData& user)
{
	//qDebug() << "删除";
	auto ret = QMessageBox::information(nullptr, "删除", QString("确认要删除%1吗？").arg(user.name()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
	if (ret & QMessageBox::No)
		return;
	model()->addMySqlThreadTask([=]
		{
			auto ok = model<MainModel>()->removeUserMySql(user);
			new XQFuncEvent(this, [=] {
				if (ok)
				{
					auto UserManagementView = (XQUserManagementView*)m_mainView->stackedWidget(MainView::View::UserManagement);
					auto tableView = UserManagementView->tableView();
					auto row= tableView->tableWidget()->currentRow();
					tableView->removeData(tableView->showRow_toIndex(row));
					tableView->tableWidget()->removeRow(row);
					emit sendMessageBoxInfoSignals(user.account() + " 删除用户", "删除成功");
				}
				else
				{
					emit sendMessageBoxInfoSignals(user.account() + " 删除用户", "删除失败");
				}
				});
		});
}
void MainController::addProductSlots(const ProductModel& product)
{
	static QDateTime currentTime = QDateTime::currentDateTime();
	if (currentTime.addSecs(1) < QDateTime::currentDateTime())
		currentTime = QDateTime::currentDateTime();
	else
		return;
	XQDebug("添加商品");
	model()->addMySqlThreadTask([=]
		{
			auto currentInventory = model<MainModel>()->currentInventory(product.name());
			if (product.number() > currentInventory)
			{
				emit sendMessageBoxInfoSignals("添加商品","数量不能大于库存量 "+QString::number(currentInventory));
				return;
			}
			auto ok = model<MainModel>()->addProductMySql(product);
			new XQFuncEvent(this, [=] {
				if (ok)
				{
					auto ManagementView = (ProductManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Product);
					auto AddView = (ProductView*)ManagementView->transcribeWidget(ProductManagementView::CreateWidget::ProductAddView);
					//XQDebug("准备关闭窗口");
					AddView->close();//
					//XQDebug("加入到表格中");
					ManagementView->addProduct(product);
					ManagementView->updataTable();
					emit sendMessageBoxInfoSignals(product.name() + " 添加商品", "添加成功");
				}
				else
				{
					emit sendMessageBoxInfoSignals(product.name() + " 添加商品", "添加失败，重复");
				}
				});
		});
}
void MainController::addProductCreateSlots(ProductView* view)
{
	connect(view, &ProductView::requestTypeSignals, [=] (const QString& name){
		model()->addMySqlThreadTask([=] {
			auto type = model<MainModel>()->InventoryType(name);
			auto currentInventory = model<MainModel>()->currentInventory(name);
			new XQFuncEvent(this, [=] {
				view->setType(type);
				view->setNumberRange(1,currentInventory);
				view->setNumber(currentInventory); 
				
				});
			});
		});
	//XQDebug("创建了新的添加窗口");
	model()->addMySqlThreadTask([=]
		{	auto id = model<MainModel>()->newProductIDMySql();
			auto typeList = model<MainModel>()->InventoryTypeList();
			auto nameList= model<MainModel>()->InventoryNameList();
	new XQFuncEvent(this, [=] {
		view->setProduct_id(id); 
		//view->setTypeCompleter(typeList);
		view->setTypeItems(typeList);
		view->setNameCompleter(nameList);
		view->setNameItems(nameList);
		});
		});
}
void MainController::modifyProductSlots(const ProductModel& product)
{
	static QDateTime currentTime = QDateTime::currentDateTime();
	if (currentTime.addSecs(1) < QDateTime::currentDateTime())
		currentTime = QDateTime::currentDateTime();
	else
		return;
	XQDebug("修改商品");
	model()->addMySqlThreadTask([=]
		{
			auto currentInventory = model<MainModel>()->currentInventory(product.name());
			if (product.number() > currentInventory)
			{
				emit sendMessageBoxInfoSignals("修改商品", "数量不能大于库存量 " + QString::number(currentInventory));
				return;
			}
			auto ok = model<MainModel>()->modifyProductMySql(product);
			if (ok)
			{
				auto ManagementView = (ProductManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Product);
				auto AddView = (ProductView*)ManagementView->transcribeWidget(ProductManagementView::CreateWidget::ProductAddView);
				new XQFuncEvent(this, [=] {
					ManagementView->setProduct(ManagementView->tableView()->currentShowRow_toIndex(), product);
					ManagementView->updataTable();
					});
				emit sendMessageBoxInfoSignals("修改商品", "更新成功");
			}
			else
			{
				emit sendMessageBoxInfoSignals("修改商品", "更新失败");
			}
		});
}
void MainController::modifyProductCreateSlots(ProductView* view)
{

	connect(view, &ProductView::requestTypeSignals, [=](const QString& name) {
		model()->addMySqlThreadTask([=] {
			auto type = model<MainModel>()->InventoryType(name);
			auto currentInventory = model<MainModel>()->currentInventory(name);
			new XQFuncEvent(this, [=] {
				view->setType(type);
				view->setNumberRange(1, currentInventory);
				view->setNumber(currentInventory);
				});
			});
		});
	//XQDebug("创建了新的添加窗口");
	model()->addMySqlThreadTask([=]
		{	
	auto currentInventory = model<MainModel>()->currentInventory(view->name());
	auto typeList = model<MainModel>()->InventoryTypeList();
	auto nameList = model<MainModel>()->InventoryNameList();
	new XQFuncEvent(this, [=] {
		//view->setProduct_id(id);
		view->setNumberRange(1, currentInventory);
		view->setTypeItems(typeList);
		view->setNameCompleter(nameList);
		view->setNameItems(nameList);
		});
		});
}
void MainController::removeProductSlots(const ProductModel& product)
{
	/*static QDateTime currentTime = QDateTime::currentDateTime();
	if (currentTime.addSecs(1) < QDateTime::currentDateTime())
		currentTime = QDateTime::currentDateTime();
	else
		return;*/
	//XQDebug("删除商品");
	auto ret = QMessageBox::information(nullptr, "删除", QString("确认要删除%1吗？").arg(product.name()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
	if (ret & QMessageBox::No)
		return;
	model()->addMySqlThreadTask([=]
		{
			auto ok = model<MainModel>()->removeProductMySql(product);
			new XQFuncEvent(this, [=] {
				if (ok)
				{
					auto ManagementView = (ProductManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Product);
					ManagementView->removeProduct(product);
					ManagementView->updataTable();
					emit sendMessageBoxInfoSignals("删除商品", "删除成功");
				}
				else
				{
					emit sendMessageBoxInfoSignals("删除商品", "删除失败");
				}
				});
		});
}
void MainController::buyProductSlots(const ProductModel& product)
{
	static QDateTime currentTime = QDateTime::currentDateTime();
	if (currentTime.addSecs(1) < QDateTime::currentDateTime())
		currentTime = QDateTime::currentDateTime();
	else
		return;
	XQDebug("下单商品");
	model()->addMySqlThreadTask([=]
		{
			auto number = model<MainModel>()->currentProductNumber(product.name());
			if (product.number() > number)
			{
				emit sendMessageBoxInfoSignals("下单","数量超出上限");
				return;
			}
			OrderModel Order;
			auto ok= model<MainModel>()->addOrderMySql(product,&Order);
			if (ok)
			{
				auto ManagementView = (ProductManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Product);
				auto buyView = (ProductView*)ManagementView->transcribeWidget(ProductManagementView::CreateWidget::ProductBuyView);
				buyView->close();

				new XQFuncEvent(this, [=] {
					auto p = ManagementView->product(ManagementView->tableView()->currentShowRow_toIndex());
					p.setNumber(p.number()- product.number());
					p.setCTime();
					ManagementView->setProduct(ManagementView->tableView()->currentShowRow_toIndex(), p); ManagementView->updataTable(); });

				auto order= (OrderManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Order);
				if (order)
				{
					new XQFuncEvent(this, [=] {order->addOrder(Order); order->updataTable(); });
					
				}
				emit sendMessageBoxInfoSignals(product.name() + "下单", "下单成功");
			}
			else
			{
				emit sendMessageBoxInfoSignals(product.name() + "下单", "下单失败");
			}
		});
}
void MainController::buyProductCreateSlots(ProductView* view)
{
	model()->addMySqlThreadTask([=]
		{
			auto currentInventory = model<MainModel>()->currentInventory(view->name());
			auto nameList = model<MainModel>()->InventoryNameList();
			new XQFuncEvent(this, [=] {
				view->setNumberRange(1, currentInventory);
				view->setNameItems(nameList);
				});
		});
}
void MainController::addInventorySlots(const InventoryModel& inventory)
{
	static QDateTime currentTime = QDateTime::currentDateTime();
	if (currentTime.addSecs(1) < QDateTime::currentDateTime())
		currentTime = QDateTime::currentDateTime();
	else
		return;
	XQDebug("添加库存");
	model()->addMySqlThreadTask([=]
		{
			auto ok = model<MainModel>()->addInventoryMySql(inventory);
			new XQFuncEvent(this, [=] {
				if (ok)
				{
					auto ManagementView = (InventoryManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Inventory);
					auto AddView = (InventoryView*)ManagementView->transcribeWidget(InventoryManagementView::CreateWidget::InventoryAddView);
					AddView->close();//
					ManagementView->addInventory(inventory);
					ManagementView->updataTable();
					emit sendMessageBoxInfoSignals(inventory.name() + " 添加库存", "添加成功");
				}
				else
				{
					emit sendMessageBoxInfoSignals(inventory.name() + " 添加库存", "添加失败");
				}
				});
		});
}
void MainController::addInventoryCreateSlots(InventoryView* view)
{
	//XQDebug("创建了新的添加窗口");
	model()->addMySqlThreadTask([=]
		{	auto id = model<MainModel>()->newInventoryIDMySql();
	new XQFuncEvent(this, [=] {view->setInventory_id(id); });
		});
}
void MainController::modifyInventorySlots(const InventoryModel& inventory)
{
	static QDateTime currentTime = QDateTime::currentDateTime();
	if (currentTime.addSecs(1) < QDateTime::currentDateTime())
		currentTime = QDateTime::currentDateTime();
	else
		return;
	XQDebug("修改库存");
	model()->addMySqlThreadTask([=]
		{
			auto ok = model<MainModel>()->modifyInventoryMySql(inventory);
			if (ok)
			{
				auto ManagementView = (InventoryManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Inventory);
				new XQFuncEvent(this, [=] {
					ManagementView->setInventory(ManagementView->tableView()->currentShowRow_toIndex(), inventory);
					ManagementView->updataTable();
					});
				emit sendMessageBoxInfoSignals(inventory.inventory_id() + "修改库存", "修改成功");
			}
			else
			{
				emit sendMessageBoxInfoSignals(inventory.inventory_id() + "修改库存", "修改失败");
			}
			
		});
}
void MainController::removeInventorySlots(const InventoryModel& inventory)
{
	/*static QDateTime currentTime = QDateTime::currentDateTime();
	if (currentTime.addSecs(1) < QDateTime::currentDateTime())
		currentTime = QDateTime::currentDateTime();
	else
		return;*/
	//XQDebug("删除库存");
	auto ret = QMessageBox::information(nullptr, "删除", QString("确认要删除%1吗？").arg(inventory.name()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
	if (ret & QMessageBox::No)
		return;
	model()->addMySqlThreadTask([=]
		{
			auto ok=model<MainModel>()->removeInventoryMySql(inventory);
			if (ok)
			{
				auto ManagementView = (InventoryManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Inventory);
				
				new XQFuncEvent(this, [=] {
					ManagementView->removeInventory(inventory);
					QMessageBox::information(view(), inventory.inventory_id() + "删除库存", "删除成功");
					});	
			}
			else
			{
				new XQFuncEvent(this, [=] {
					QMessageBox::information(view(), inventory.inventory_id() + "删除库存", "删除失败");
					});
			}
		});
}
void MainController::init()
{
	setModel(new MainModel);
	m_mainView = new MainView();
	m_mainView->init();
	QObject::connect(m_mainView, &QWidget::destroyed, this, &QObject::deleteLater);
	QObject::connect(m_mainView, &MainView::modifyUserInfoSignals, this, &MainController::modifyUserInfoSlots);
	QObject::connect(m_mainView, &MainView::modifyPasswordSignals, this, &MainController::modifyPasswordSlots);
	QObject::connect(m_mainView, &MainView::userManagementSignals, this, &MainController::modifyUserManagementSlots);
	QObject::connect(m_mainView, &MainView::addUserSignals, this, &MainController::addUserManagementSlots);
	QObject::connect(m_mainView, &MainView::removeUserSignals, this, &MainController::removeUserManagementSlots);

	init_catalogue();
	installEventFilter(new XQFuncEventFilter(this));
}

void MainController::init_catalogue()
{
	init_login();
	init_openUserInfo();
	init_openModifyPassword();
	init_openUserManagement();
	init_openProductManagement();
	init_openInventoryManagement();
	init_openOrderManagement();
}

void MainController::init_login()
{
	auto catalogue = m_mainView->catalogue();
	catalogue->setItemClickedFunc(XQTreeDockWidget::Item::Login, [=] {emit requestLoginSignals(); });
}

void MainController::init_openUserInfo()
{
	auto catalogue = m_mainView->catalogue();
	catalogue->setItemClickedFunc(XQTreeDockWidget::Item::UserInfo, [=] {m_mainView->openUserInfoView(model()->userData()); });
}

void MainController::init_openModifyPassword()
{
	auto catalogue = m_mainView->catalogue();
	catalogue->setItemClickedFunc(XQTreeDockWidget::Item::ModifyPassword, [=] {m_mainView->openModifyPasswordView(model()->userData()); });
}

void MainController::init_openUserManagement()
{
	auto catalogue = m_mainView->catalogue();
	catalogue->setItemClickedFunc(XQTreeDockWidget::Item::UserManagement, [=] {
		m_mainView->openUserManagement(model()->userData());
		auto view = (XQUserManagementView*)m_mainView->stackedWidget(MainView::View::UserManagement);
		view->setEnabled(false);
		emit m_mainView->showMessage("正在查询用户中");
		model()->addMySqlThreadTask([=] {
			auto list=model<MainModel>()->userListMySql();
			new XQFuncEvent(this, [=] {
				view->setUser(list);
				view->showUser();
				view->setEnabled(true);
				emit m_mainView->showMessage("查询到用户"+QString::number(list.size())+"条",5000);

				});
			});

		});
}

void MainController::init_openProductManagement()
{
	auto catalogue = m_mainView->catalogue();
	catalogue->setItemClickedFunc(MainView::Catalogue::Product, [=] {
		m_mainView->openProductManagement(model()->userData()); 
		auto view = (ProductManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Product);
		connect(view, &ProductManagementView::addProductSignals, this, &MainController::addProductSlots);
		connect(view, &ProductManagementView::addProductCreateSignals, this, &MainController::addProductCreateSlots);
		connect(view, &ProductManagementView::modifyProductSignals, this, &MainController::modifyProductSlots);
		connect(view, &ProductManagementView::modifyProductCreateSignals, this, &MainController::modifyProductCreateSlots);
		connect(view, &ProductManagementView::removeProductSignals, this, &MainController::removeProductSlots);
		connect(view, &ProductManagementView::buyProductSignals, this, &MainController::buyProductSlots);
		connect(view, &ProductManagementView::buyProductCreateSignals, this, &MainController::buyProductCreateSlots);

		if (model()->userData().permission() == XQUserData::Permission::user)
			view->setHideOperationButtons(true);
		//初始化
		model()->addMySqlThreadTask([=]
			{	auto list = model<MainModel>()->ProductListMySql();
		new XQFuncEvent(this, [=] {view->setProduct(list); view->updataTable(); });
			});
		
		});
}

void MainController::init_openInventoryManagement()
{
	auto catalogue = m_mainView->catalogue();
	catalogue->setItemClickedFunc(MainView::Catalogue::Inventory, [=] {
		m_mainView->openInventoryManagement(model()->userData()); 
	auto view = (InventoryManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Inventory);
	
	QObject::connect(view, &InventoryManagementView::addInventorySignals, this, &MainController::addInventorySlots);
	QObject::connect(view, &InventoryManagementView::modifyInventorySignals, this, &MainController::modifyInventorySlots);
	QObject::connect(view, &InventoryManagementView::removeInventorySignals, this, &MainController::removeInventorySlots);
	//添加窗口初始化
	connect(view, &InventoryManagementView::addInventoryCreateSignals, this, &MainController::addInventoryCreateSlots);

	model()->addMySqlThreadTask([=]
		{	auto list = model<MainModel>()->InventoryListMySql();
	new XQFuncEvent(this, [=] {view->setInventory(list); view->updataTable(); });
		});

	});
}

void MainController::init_openOrderManagement()
{
	auto catalogue = m_mainView->catalogue();
	catalogue->setItemClickedFunc(MainView::Catalogue::Order, [=] {m_mainView->openOrderManagement(model()->userData()); 
	auto view = (OrderManagementView*)m_mainView->stackedWidget(MainView::MainView::Catalogue::Order);
		
	model()->addMySqlThreadTask([=]
		{	
			QList<OrderModel> list;
			if(model()->userInfo()->permission()==XQUserData::Permission::user)
				list = model<MainModel>()->OrderListMySql(model()->userInfo()->account());
			else
				list = model<MainModel>()->OrderListMySql();
			new XQFuncEvent(this, [=] {view->setOrder(list); view->updataTable(); });
		});
		
		});
}
